<template>
  <el-card class="box-card">
    <div class="row">
      <el-icon>
        <Search />
      </el-icon>
      <span>筛选搜索</span>
      <el-button @click="Reset">重置</el-button>
      <el-button type="primary" @click="searchHandle">查询搜索</el-button>
    </div>
    <el-form :model="form" label-width="140px">
      <el-form-item label="输入搜索：">
        <el-input v-model="form.keyword" placeholder="商品名称" style="width:210px" />
      </el-form-item>
      <el-form-item label="商品货号：">
        <el-input v-model="form.productSn" placeholder="商品货号" style="width:210px" />
      </el-form-item>
      <el-form-item label="商品分类：">
        <el-cascader :options="productCategoryList" clearable @change="handleChange"
          :props="{ label: 'name', value: 'id', children: 'children' }" v-model="productCategoryId">
        </el-cascader>
      </el-form-item>
      <el-form-item label="商品品牌：">
        <el-select v-model="form.brandId" placeholder="请选择品牌" clearable>
          <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态：">
        <el-select v-model="form.publishStatus" placeholder="全部" clearable>
          <el-option :value="0">上架</el-option>
          <el-option :value="1">下架</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态：">
        <el-select v-model="form.verifyStatus" placeholder="全部" clearable>
          <el-option :value="0">未审核</el-option>
          <el-option :value="1">审核通过</el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card class="box-card">
    <div class="row">
      <el-icon>
        <Tickets />
      </el-icon>
      <span>数据列表</span>
      <el-button type="primary" @click="router.push('/pms/addProduct')" v-permission="'addProduct'">添加</el-button>
    </div>
  </el-card>
  <el-table :data="list" border table-layout="auto" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="编号" />
    <el-table-column label="商品图片">
      <template #default="{ row }">
        <el-image style="width: 100px; height: 100px" :src="row.pic" />
      </template>
    </el-table-column>
    <el-table-column label="商品名称">
      <template #default="{ row }">
        <p>{{ row.name }}</p>
        品牌:{{ row.brandName }}
      </template>
    </el-table-column>
    <el-table-column label="价格/货号">
      <template #default="{ row }">
        <p>价格:￥{{ row.price }}</p>
        货号：{{ row.productSn }}
      </template>
    </el-table-column>
    <el-table-column label="标签">
      <template #default="{ row }">
        <p>上架：<el-switch v-model="row.publishStatus" :active-value="1" :inactive-value="0"
            @click="PublishStatus(row.id, row.publishStatus)" /></p>
        <p>新品：<el-switch v-model="row.newStatus" :active-value="1" :inactive-value="0"
            @click="NewStatus(row.id, row.newStatus)" /></p>

        <p>推荐：<el-switch v-model="row.recommandStatus" :active-value="1" :inactive-value="0"
            @click="RecommendStatus(row.id, row.recommandStatus)" /></p>
      </template>
    </el-table-column>
    <el-table-column prop="sort" label="排序" />
    <el-table-column label="sku库存">
      <template #default="{ row }">
        <el-button type="primary" :icon="EditPen" circle size="large" @click="isShowDialog = true, Sku.pid = row.id" />
      </template>
    </el-table-column>
    <el-table-column prop="sale" label="销量" />
    <el-table-column label="审核状态">
      <template #default="{ row }">
        <p>{{ row.verifyStatus == 0 ? '未审核' : '审核中' }}</p>
        <el-button type="primary" text>审核详细</el-button>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button type="primary" @click="router.push(`/pms/updateProduct?id=${row.id}`)"
          v-permission="'updateProduct'">编辑</el-button>
        <el-button type="danger" @click="del(row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="batch">
    <el-select v-model="batch" placeholder="全部" clearable>
      <el-option value="商品上架">商品上架</el-option>
      <el-option value="商品下架">商品下架</el-option>
      <el-option value="设为推荐">设为推荐</el-option>
      <el-option value="取消推荐">取消推荐</el-option>
      <el-option value="设为新品">设为新品</el-option>
      <el-option value="取消新品">取消新品</el-option>
      <el-option value="转移到分类">转移到分类</el-option>
      <el-option value="移入回收站">移入回收站</el-option>
    </el-select>
    <el-button @click="batchBtn" type="primary">确定</el-button>
    <el-config-provider :locale="zhCn">
      <div class="page">
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="pageChangeHandle"
          @current-change="pageSizeChangeHandle" />
      </div>
    </el-config-provider>
  </div>
  <el-dialog v-model="isShowDialog" title="编辑货物信息" @close="isShowDialog = false">
    <el-form :model="Sku" label-width="140px">
      <el-form-item label="商品货号：">
        <el-input v-model="Sku.keywords" placeholder="按sku编号搜索" style="width:140">
          <template #append>
            <el-button :icon="Search" @click="search" />
          </template></el-input>
      </el-form-item>
      <el-table :data="SkuList">
        <el-table-column property="skuCode" label="SKU编号" />
        <el-table-column property="price" label="销售价格" />
        <el-table-column property="stock" label="商品库存" />
        <el-table-column property="lowStock" label="库存预售值" />
      </el-table>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isShowDialog = false">取消</el-button>
        <el-button type="primary" @click="OkBtn">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import useTable from "@/hooks/useTable";
import { reactive, ref } from "vue";
import { ApiGetProductList, ApiGetProductCategoryWithChildren, ApiGetBrandListAll, ApiGetSku, ApiUpDataSku, ApiDeleteProductAttr, ApiNewStatus, ApiRecommendStatus, ApiPublishStatus } from "./api";
import { ElConfigProvider, ElMessage, ElMessageBox } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { Tickets, Search, EditPen } from '@element-plus/icons-vue'
import { useRouter } from "vue-router";
const router = useRouter()
const ids = ref<number[]>([])//id数组
const publishStatus = ref(0)// 上架状态
// 修改商品上架
const SwitchProductPublishStatus = () => {
  ApiPublishStatus(ids.value, publishStatus.value).then(res => {
    if (res.code == 200) {
      ElMessage.success("修改成功");
    } else {
      ElMessage.success("修改失败");
      searchHandle()
    }
    ids.value = []
  })
}
// 单个上架
const PublishStatus = (id: number, status: number) => {
  ids.value = [id]
  publishStatus.value = status
  SwitchProductPublishStatus()
}
const recommendStatus = ref(0)// 推荐状态
// 修改商品推荐
const SwitchProductRecommendStatus = () => {
  ApiRecommendStatus(ids.value, recommendStatus.value).then(res => {
    if (res.code == 200) {
      ElMessage.success("修改成功");
    } else {
      ElMessage.success("修改失败");
      searchHandle()
    }
    ids.value = []
  })
}
// 单个推荐
const RecommendStatus = (id: number, status: number) => {
  ids.value = [id]
  recommendStatus.value = status
  SwitchProductRecommendStatus()
}
const newStatus = ref(0)// 新品状态
// 修改商品新品
const SwitchProductNewStatus = () => {
  ApiNewStatus(ids.value, newStatus.value).then(res => {
    if (res.code == 200) {
      ElMessage.success("修改成功");
    } else {
      ElMessage.success("修改失败");
      searchHandle()
    }
    ids.value = []
  })
}
// 单个新品
const NewStatus = (id: number, status: number) => {
  ids.value = [id]
  newStatus.value = status
  SwitchProductNewStatus()
}
const deleteStatus = ref(0)// 删除状态
// 删除商品
const deleteProduct = () => {
  ApiDeleteProductAttr(ids.value, deleteStatus.value).then(res => {
    if (res.code == 200) {
      ElMessage.success("删除成功");
      searchHandle()
    } else {
      ElMessage.success("删除失败");
    }
    ids.value = []
  })
}
// 单个删除
const del = (id: number) => {
  // 二次确定
  ElMessageBox.confirm("确定要删除商品吗？", "删除商品", {
    confirmButtonText: "确定", cancelButtonText: "取消", type: "warning",
  }).then(() => {
    ids.value = [id]
    deleteStatus.value = 1
    deleteProduct()
  }).catch(() => {
    console.log("点击的取消");
  });
}
// 多选框操作
const handleSelectionChange = (val: IProductModel[]) => {
  ids.value = val.map(item => item.id)
  console.log(ids.value);
}
// 批量操作
const batch = ref('')
const batchBtn = () => {
  ElMessageBox.confirm("是否要进行该批量操作?", "批量操作", {
    confirmButtonText: "确定", cancelButtonText: "取消", type: "warning",
  }).then(() => {
    if (ids.value.length !== 0) {
      if (batch.value == '商品上架') {
        publishStatus.value = 1
        SwitchProductPublishStatus()
      } else if (batch.value == '商品下架') {
        publishStatus.value = 0
        SwitchProductPublishStatus()
      } else if (batch.value == '设为推荐') {
        recommendStatus.value = 1
        SwitchProductRecommendStatus()
      } else if (batch.value == '取消推荐') {
        recommendStatus.value = 0
        SwitchProductRecommendStatus()
      } else if (batch.value == '设为新品') {
        newStatus.value = 1
        SwitchProductNewStatus()
      } else if (batch.value == '取消新品') {
        newStatus.value = 0
        SwitchProductNewStatus()
      } else if (batch.value == '转移到分类') {
        deleteStatus.value = 0
        deleteProduct()
      } else if (batch.value == '移入回收站') {
        deleteStatus.value = 1
        deleteProduct()
      }
      searchHandle()
    } else {
      ElMessage.warning("还未选择商品")
    }
  }).catch(() => {
    console.log("点击的取消");
  });


}
const form = reactive({
  keyword: "", //商品名称模糊关键字
  productSn: "",//商品货号
  brandId: '',//商品品牌编号
  productCategoryId: '',//商品分类编号
  publishStatus: '',//上架状态
  verifyStatus: ''//审核状态
});
// 分类选择改变时
const handleChange = () => {
  form.productCategoryId = productCategoryId.value[productCategoryId.value.length - 1]
  // console.log(productCategoryId.value[productCategoryId.value.length - 1]);
}
const productCategoryId = ref('')
// 商品分类
const productCategoryList = ref<IProductCategoryWithChildren[]>();
// 品牌分类
const brandList = ref<IBrandList[]>([]);
// 重置
const Reset = () => {
  form.keyword = "";
  form.productSn = ""
  form.brandId = ''
  form.publishStatus = ''
  form.verifyStatus = ''
  form.productCategoryId = ''
}
// 是否显示Dialog
const isShowDialog = ref(false)
// skuList
const SkuList = ref<ISku[]>([])
// Sku表单
const Sku = reactive({
  pid: 0,
  keywords: ''
})
// sku搜索
const search = () => {
  ApiGetSku(Sku.pid, Sku.keywords).then(res => {
    if (res.code == 200) {
      SkuList.value = res.data
    }
  })
}
// Sku确定
const OkBtn = () => {
  if (SkuList.value.length == 0) {
    ElMessage.warning("暂无Sku信息")
  } else {
    ApiUpDataSku(Sku.pid, SkuList.value).then(res => {
      console.log(res);
    })
  }
  isShowDialog.value = false
}
// 获取商品分类
ApiGetProductCategoryWithChildren().then(res => {
  if (res.code == 200) {
    productCategoryList.value = res.data
  }
})
// 获取品牌分类
ApiGetBrandListAll().then(res => {
  if (res.code == 200) {
    brandList.value = res.data
  }
})
const {
  list,
  pageNum,
  pageSize,
  total,
  pageChangeHandle,
  pageSizeChangeHandle,
  searchHandle,
} = useTable(ApiGetProductList, form);
</script>
<style lang="less" scoped>
:deep(.el-table__inner-wrapper) {
  font-size: 12px;
}

:deep(.el-table__cell) {
  text-align: center;
}

.box-card {
  margin-bottom: 20px;

  .row {
    display: flex;
    align-items: center;

    span {
      flex: 1;
    }

  }

  :deep(.el-form) {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
  }

}

.batch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;

  :deep(.el-button) {
    margin-left: 20px;
  }
}

.page {
  flex: 1;

  :deep(.el-pagination) {
    justify-content: flex-end;
  }
}
</style>